package me.android.library.utils.android;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.AppOpsManager;
import android.app.Application;
import android.app.usage.UsageStatsManager;
import android.content.pm.ApplicationInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Process;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import mylab.utils.common.StringUtil;

@Slf4j
@UtilityClass
public class AppUtil {

    // 应用前后台状态标记
    private final AtomicBoolean isAppInBackground = new AtomicBoolean(true);

    /**
     * 初始化应用前后台状态监听（需在 Application 中调用）
     *
     * @param application Application 实例
     */
    public void initAppStateListener(Application application) {
        application.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
            private int activityCount = 0;

            @Override
            public void onActivityStarted(@NonNull android.app.Activity activity) {
                if (activityCount == 0) {
                    // 从后台进入前台
                    isAppInBackground.set(false);
                }
                activityCount++;
            }

            @Override
            public void onActivityStopped(@NonNull android.app.Activity activity) {
                activityCount--;
                if (activityCount == 0) {
                    // 从前台进入后台
                    isAppInBackground.set(true);
                }
            }

            @Override
            public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {

            }

            @Override
            public void onActivityResumed(@NonNull Activity activity) {

            }

            @Override
            public void onActivityPaused(@NonNull Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(@NonNull Activity activity) {

            }
        });
    }

    /**
     * 检查应用是否在后台（推荐方法，使用 Activity 生命周期监听）
     *
     * @return true 表示应用在后台，false 表示在前台
     */
    public boolean isAppInBackground() {
        return isAppInBackground.get();
    }

    public boolean isNamedProcess(String processName) {
        int pid = android.os.Process.myPid();
        ActivityManager manager = SystemServiceUtil.getActivityManager();
        List<RunningAppProcessInfo> processInfoList = manager.getRunningAppProcesses();
        if (processInfoList == null) {
            return true;
        }

        for (RunningAppProcessInfo processInfo : manager
                .getRunningAppProcesses()) {
            if (processInfo.pid == pid
                    && Objects.equals(processName, processInfo.processName)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检查应用是否在前台（兼容 Android 5.0+）
     *
     * @param packageName 应用包名
     * @return true 表示在前台，false 表示不在前台或无法判断
     */
    public boolean isAppInForeground(String packageName) {
        if (StringUtil.isEmpty(packageName)) {
            return false;
        }

        // Android 10+ 使用 UsageStatsManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            return isAppInForegroundQ(packageName);
        }

        // Android 5.0-9.0 使用 ActivityManager.getRunningAppProcesses()
        ActivityManager activityManager = SystemServiceUtil.getActivityManager();
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        if (appProcesses == null) {
            return false;
        }

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
                    && appProcess.processName.equals(packageName)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Android 10+ 检查应用是否在前台
     */
    @RequiresApi(api = Build.VERSION_CODES.Q)
    private boolean isAppInForegroundQ(String packageName) {
        try {
            // 获取 UsageStatsManager
            AppOpsManager appOps = SystemServiceUtil.getAppOpsManager();
            long currentTime = System.currentTimeMillis();

            // 检查是否有查询使用情况的权限
            if (appOps != null) {
                int mode = appOps.checkOpNoThrow(
                        AppOpsManager.OPSTR_GET_USAGE_STATS,
                        Process.myUid(),
                        ContextUtil.getAppContext().getPackageName()
                );

                if (mode != AppOpsManager.MODE_ALLOWED) {
                    Log.w("AppUtils", "Missing GET_USAGE_STATS permission");
                    return false;
                }
            }

            // 查询最近的应用使用情况
            UsageStatsManager usageStatsManager = SystemServiceUtil.getUsageStatsManager();
            if (usageStatsManager == null) {
                return false;
            }

            // 获取最近 10 秒内的应用使用情况
            List<android.app.usage.UsageStats> stats = usageStatsManager.queryUsageStats(
                    android.app.usage.UsageStatsManager.INTERVAL_BEST,
                    currentTime - 10000,
                    currentTime
            );

            if (stats != null && !stats.isEmpty()) {
                // 按最后使用时间排序
                stats.sort((a, b) -> Long.compare(b.getLastTimeUsed(), a.getLastTimeUsed()));
                return packageName.equals(stats.get(0).getPackageName());
            }
        } catch (Exception e) {
            Log.e("AppUtils", "Error checking foreground app", e);
        }

        return false;
    }

    public boolean isDebug() {
        return (0 != (ContextUtil.getAppContext().getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE));
    }
}
